package com.imcoke.abchat.filter;

import com.imcoke.abchat.common.AppProperties;
import com.imcoke.abchat.common.utils.JwtTokenUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author ccoke
 * @Description
 * @Date: 9:51 2017-11-29
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private AppProperties appProperties;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private UserDetailsService userDetailsService;
    private static final String USERNAME = "username";

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        String authHeader = request.getHeader(appProperties.getJwt_header());
        if(authHeader != null && authHeader.startsWith(appProperties.getJwt_tokenHead())){
            final String authToken = authHeader.substring(appProperties.getJwt_tokenHead().length());
            String username = null;
            Boolean flag = false;
            try {
                Claims claims = jwtTokenUtil.getClaimsFromToken(authToken);
                // 从token中获取用户名
                username  = (String)claims.get(USERNAME);
                flag = true;
            }catch (Exception e){
                //如果过期，或者token无效,则会抛出异常
                logger.info("无效的token");
            }
            if (flag && username != null && SecurityContextHolder.getContext().getAuthentication() == null){
                UserDetails userDetails = userDetailsService.loadUserByUsername(username);
                if (jwtTokenUtil.validateToken(authToken,userDetails)){
                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                            userDetails, null, userDetails.getAuthorities());
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(
                            request));
                    logger.info("authenticated user " + username + ", setting security context");
                    //在全局上下文中设置用户名
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }
            }
        }
        chain.doFilter(request,response);
    }
}
